~ chicken-core (master) /manual/Getting started
Trap1[[tags: manual]]23== Getting started45CHICKEN is a compiler that translates Scheme source files into6C, which in turn can be fed to a C compiler to generate a7standalone executable. An interpreter is also available and can be8used as a scripting environment or for testing programs before9compilation.1011This chapter is designed to get you started with CHICKEN programming,12describing what it is and what it will do for you, and covering basic13use of the system. With almost everything discussed here, there is14more to the story, which the remainder of the manual reveals. Here, we15only cover enough to get you started. Nonetheless, someone who knows16Scheme already should be able to use this chapter as the basis for17writing and running small CHICKEN programs.1819=== Scheme2021Scheme is a member of the Lisp family of languages, of which Common22Lisp, Emacs Lisp and Clojure are other widely-known members. As with23Lisp dialects, Scheme features2425* a wide variety of programming paradigms, including imperative, functional, and object-oriented26* a very simple syntax, based upon nested parenthesization27* the ability to extend the language in meaningful and useful ways2829In contrast to Common Lisp, Scheme is very minimal, and tries to30include only those features absolutely necessary in programming. In31contrast to Emacs Lisp, Scheme is not anchored into a single program32(Emacs), and has a more modern and elegant language design. In contrast33to Clojure, Scheme provides only a very minimal set of concepts but allows34them to be used in very general ways with few restrictions.3536Scheme is defined in a document called ''The Revised^7 Report on the37Algorithmic Language Scheme'', or ''R7RS'' for short. (Yes, it really38has been revised seven times, so an expanded version of its name would39be ''The Revised Revised Revised Revised Revised Report''.)4041CHICKEN fully complies with R7RS.4243Even though Scheme is consciously minimalist, it is recognized that a44language must be more than a minimal core in order to be45useful. Accordingly, the Scheme community uses a process known as46`Scheme Requests For Implementation' (SRFI, pronounced `SUR-fee') to47define new language features. A typical Scheme system therefore48complies with one of the Scheme reports plus some or all of the49accepted SRFIs.5051A good starting point for Scheme knowledge is52[[http://www.schemers.org]]. There you will find the defining reports,53FAQs, lists of useful books and other resources, and the SRFIs.5455=== CHICKEN5657CHICKEN Scheme combines an optimising compiler with a reasonably fast58interpreter. It supports all of R7RS and the important SRFIs.59The compiler generates portable C code that supports tail recursion,60first-class continuations and lightweight threads, and the interface to61and from C libraries is flexible, efficient, and easy to use. There are62hundreds of contributed CHICKEN libraries that make the programmer's63task easier. The interpreter allows interactive use, fast prototyping,64debugging, and scripting. The active and helpful CHICKEN community65fixes bugs and provides support. Extensive documentation is supplied.6667CHICKEN was developed by Felix L. Winkelmann over the period from 200068through 2007. In early 2008, Felix69asked the community to take over the responsibility of developing and70maintaining the system, though he still takes a strong interest in it,71and participates actively.7273CHICKEN includes7475* a Scheme interpreter that supports all of R7RS Scheme, with76 only a few relatively minor omissions, and with many extensions77* a compatible compiler whose target is C, thus making porting to new78 machines and architectures relatively straightforward79* the C support allows Scheme code to include `embedded' C code,80 thus making it easy to invoke host OS or library81 functions82* a framework for language extensions, library modules that broaden83 the functionality of the system8485This package is distributed under the '''BSD license''' and as such is free86to use and modify as long as the original authors are acknowledged.8788Scheme cognoscenti will appreciate the method of compilation and the89design of the runtime-system, which follow closely Henry Baker's90[[https://web.archive.org/web/20200223051632/http://home.pipeline.com/~hbaker1/CheneyMTA.html|CONS Should Not91CONS Its Arguments, Part II: Cheney on the M.T.A.]] paper and expose a92number of interesting properties.9394* Consing (creation of data on the heap) is inexpensive,95 because a generational garbage collection scheme is used in combination96 with allocating on the C stack, in which short-lived data structures are reclaimed97 extremely quickly.9899* Moreover, {{call-with-current-continuation}} involves only minimal100 overhead and CHICKEN does not suffer under any performance penalties if101 first-class continuations are used in complex ways.102103The generated C code fully supports tail-call optimization (TCO).104105Some of the features supported by CHICKEN:106107* Lightweight threads based on first-class continuations108* Record structures109* Extended comment- and string-literal syntaxes110* Libraries for regular expressions, string handling111* UNIX system calls and extended data structures112* Compiled C files can be easily distributed113* Allows the creation of fully self-contained statically linked executables114* On systems that support it, compiled code can be loaded dynamically115* Built-in support for cross-compilation116117CHICKEN has been used in many environments ranging from embedded118systems through desktop machines to large-scale server deployments.119The number of language extensions, or '''eggs''', is constantly growing:120121* extended language features122* development tools, such as documentation generators, debugging, and123 automated testing libraries124* interfaces to other languages such as Java, Python, and Objective-C125* interfaces to database systems, GUIs, and other libraries,126* network applications, such as servers and clients for ftp,127 smtp/pop3, irc, and http128* web servers and related tools, including URL parsing, HTML129 generation, AJAX, and HTTP session management130* data formats, including XML, JSON, and Unicode support131132This chapter provides you with an overview of the entire system, with133enough information to get started writing and running small Scheme134programs.135136=== CHICKEN repositories, websites and community137138The master CHICKEN website is139[[http://www.call-cc.org]]. Here you can find140basic information about CHICKEN, downloads and pointers to other key141resources.142143The CHICKEN wiki ([[http://wiki.call-cc.org]]) contains the most144current version of the User's manual, along with various tutorials and145other useful documents. The list of eggs is at146[[http://wiki.call-cc.org/egg-index|http://wiki.call-cc.org/egg-index]].147148A very useful search facility for questions about procedures and syntax149available for CHICKEN can be found at150[[http://api.call-cc.org]]. The CHICKEN issue tracker is at151[[http://bugs.call-cc.org]].152153The CHICKEN community has two major mailing lists. If you are a154CHICKEN user, {{chicken-users}}155([[http://lists.nongnu.org/mailman/listinfo/chicken-users]]) will be156of interest. The crew working on the CHICKEN system itself uses the157very low-volume {{chicken-hackers}} list158([[http://lists.nongnu.org/mailman/listinfo/chicken-hackers]]) for159communication. For other topic-specific mailing lists (e.g.,160announcements, security) and discussion groups, see161[[http://wiki.call-cc.org/discussion-groups|http://wiki.call-cc.org/discussion-groups]].162163There is also an IRC channel ({{#chicken}}) on164[[http://libera.chat|Libera.Chat]].165166=== Installing CHICKEN167168CHICKEN is available as C sources. Refer to the169{{README}} file in the distribution for instructions on installing it170on your system.171172Because it compiles to C, CHICKEN requires that a C compiler be173installed on your system. (If you're not writing embedded C code, you174can pretty much ignore the C compiler once you have installed it.)175176* On a Linux system, a C toolchain (e.g., GCC, clang) should be177 installed as part of the basic operating system, or should be178 available through the package management system (e.g., APT,179 Synaptic, RPM, or Yum, depending upon your Linux distribution).180* On Macintosh OS X, you will need the XCode tools, which are181 installable from the App Store.182* On Windows, you have two choices:183* Cygwin ([[https://www.cygwin.com/]]) provides a relatively184 full-featured Unix environment for Windows. CHICKEN works185 substantially the same in Cygwin and Unix.186* The GNU Compiler Collection has been ported to Windows, in the187 MinGW system. Unlike Cygwin,188 executables produced with MinGW do not need the Cygwin DLLs in order189 to run.190191Refer to the {{README}} file for the version you're installing for192more information on the installation process.193194Alternatively, third party packages in binary format are195available. See196[[http://wiki.call-cc.org/platforms|http://wiki.call-cc.org/platforms]]197for information about how to obtain them.198199=== Development environments200201The simplest development environment is a text editor and terminal202window (Windows: Command Prompt, OSX: Terminal, Linux/Unix: xterm) for203using the interpreter and/or invoking the compiler. If you install one204of the line editing extensions (e.g., [[/egg/breadline|breadline]], [[/egg/linenoise|linenoise]]), you have some205useful command line editing features in the interpreter (e.g., Emacs206or vi-compatible line editing, customization).207208It will be helpful to use a text editor that knows Scheme; it can be painful209with editors that don't do parenthesis matching and automatic210indentation.211212In the rest of this chapter, we'll assume that you are using an editor213of your choice and a regular terminal window for executing your214CHICKEN code.215216=== The Read-Eval-Print loop217218To invoke the CHICKEN interpreter, you use the {{csi}} command.219220 $ csi221 CHICKEN222 (c) 2008-2021, The CHICKEN Team223 (c) 2000-2007, Felix L. Winkelmann224 Version 5.3.0 (rev e31bbee5)225 linux-unix-gnu-x86-64 [ 64bit dload ptables ]226227 Type ,? for help.228 #;1>229230This brings up a brief banner, and then the prompt. You can use this231pretty much like any other Scheme system, e.g.,232233 #;1> (define (twice f) (lambda (x) (f (f x))))234 #;2> ((twice (lambda (n) (* n 10))) 3)235 300236237Suppose we have already created a file {{fact.scm}} containing a238function definition.239240 (define (fact n)241 (if (= n 0)242 1243 (* n (fact (- n 1)))))244245We can now load this file and try out the function.246247 #;3> (load "fact.scm")248 ; loading fact.scm ...249 #;4> (fact 3)250 6251252The '''read-eval-print loop''' ('''REPL''') is the component of the253Scheme system that ''reads'' a Scheme expression, ''eval''uates it,254and ''prints'' out the result. The REPL's prompt can be customized255(see the [[Using the interpreter]])256but the default prompt, showing the number of the form, is quite257convenient.258259The REPL also supports debugging commands:260input lines beginning with a {{,}} (comma) are treated as special261commands. (See the [[Using the interpreter#Toplevel commands|full list]].)262263264==== Scripts265266You can use the interpreter to run a Scheme program from the command267line. For the following example we create a program that does a quick268search-and-replace on an input file; the arguments are a regular269expression and a replacement string. First create a file to hold the "data" called ''quickrep.dat'' with your favorite editor holding these lines:270271 xyzabcghi272 abxawxcgh273 foonly274275Next create the scheme code in a file called ''quickrep.scm'' with the276following little program:277278<enscript highlight=scheme>279;; irregex, the regular expression library, is one of the280;; libraries included with CHICKEN.281(import (chicken irregex)282 (chicken io))283284(define (process-line line re rplc)285 (irregex-replace/all re line rplc))286287(define (quickrep re rplc)288 (let ((line (read-line)))289 (if (not (eof-object? line))290 (begin291 (display (process-line line re rplc))292 (newline)293 (quickrep re rplc)))))294295;;; Does a lousy job of error checking!296(define (main args)297 (quickrep (irregex (car args)) (cadr args)))298</enscript>299300301To run it enter this in your shell:302303 $ csi -ss quickrep.scm <quickrep.dat 'a.*c' A304 xyzAghi305 Agh306 foonly307308The {{-ss}} option sets several options that work smoothly together to309execute a script. You can make the command directly executable from310the shell by inserting a [[Using the interpreter#Writing Scheme scripts|shebang line]]311at the beginning of the program.312313The {{-ss}} option arranges to call a procedure named {{main}}, with314the command line arguments, packed in a list, as its arguments. (There315are a number of ways this program could be made more idiomatic CHICKEN316Scheme, see the rest of the manual for details.)317318=== The compiler319320There are several reasons you might want to compile your code.321322* Compiled code executes substantially faster than interpreted323 code.324* You might want to deploy an application onto machines where the325 users aren't expected to have CHICKEN installed: compiled326 applications can be self-contained.327* Compiled code can access external libraries written in lower-level328 languages that follow the C calling convention.329330The CHICKEN compiler is provided as the command {{chicken}}, but in331almost all cases, you will want to use the {{csc}} command332instead. {{csc}} is a convenient driver that automates compiling333Scheme programs into C, compiling C code into object code, and linking334the results into an executable file. (Note: in a Windows environment335with Visual Studio, you may find that {{csc}} refers to Microsoft's336C# compiler. There are a number of ways of sorting this out, of which337the simplest is to rename one of the two tools, and/or to338organize your {{PATH}} according to the task at hand.)339340We can compile our factorial function, producing a file named341{{fact.so}} (''shared object'' in Linux-ese, the same file extension is342used in Windows, rather than {{dll}})343344 chicken$ csc -shared fact.scm345 chicken$ csi -quiet346 #;1> (load "fact.so")347 ; loading fact.so ...348 #;2> (fact 6)349 720350351On any system, we can just compile a program directly into an352executable. Here's a program that tells you whether its argument is a353palindrome.354355<enscript highlight=scheme>356(import (chicken process-context)) ; for "command-line-arguments"357358(define (palindrome? x)359 (define (check left right)360 (if (>= left right)361 #t362 (and (char=? (string-ref x left) (string-ref x right))363 (check (add1 left) (sub1 right)))))364 (check 0 (sub1 (string-length x))))365366(let ((arg (car (command-line-arguments))))367 (display368 (string-append arg369 (if (palindrome? arg)370 " is a palindrome\n"371 " isn't a palindrome\n"))))372</enscript>373374We can compile this program using {{csc}}, creating an executable375named {{palindrome}}.376377 $ csc -o palindrome palindrome.scm378 $ ./palindrome level379 level is a palindrome380 $ ./palindrome liver381 liver isn't a palindrome382383CHICKEN supports separate compilation, using some extensions to384Scheme. Let's divide our palindrome program into a library module385({{pal-proc.scm}}) and a client module ({{pal-user.scm}}).386387Here's the external library. We {{declare}} that {{pal-proc}} is a388''unit'', which is the basis of separately-compiled modules in389CHICKEN. (Units deal with separate compilation, but don't necessarily390involve separated namespaces; namespaces can be implemented by391[[/manual/Modules|modules]].)392393<enscript highlight=scheme>394;;; Library pal-proc.scm395(declare (unit pal-proc))396397(define (palindrome? x)398 (define (check left right)399 (if (>= left right)400 #t401 (and (char=? (string-ref x left) (string-ref x right))402 (check (add1 left) (sub1 right)))))403 (check 0 (sub1 (string-length x))))404</enscript>405406Next we have some client code that ''uses'' this separately-compiled407module.408409<enscript highlight=scheme>410;;; Client pal-user.scm411(declare (uses pal-proc))412413(import (chicken process-context))414415(let ((arg (car (command-line-arguments))))416 (display417 (string-append arg418 (if (palindrome? arg)419 " is a palindrome\n"420 " isn't a palindrome\n"))))421</enscript>422423Now we can compile and link everything together. (We show the compile424and link operations separately, but they can of course be combined425into one command.)426427 $ csc -c pal-proc.scm428 $ csc -c pal-user.scm429 $ csc -o pal-separate pal-proc.o pal-user.o430 $ ./pal-separate level431 level is a palindrome432433The "unit" mechanism is relatively low-level and requires some434familiarity with underlying mechanism used to manage compilation435units. See [[Units and linking model]] for more information.436437=== Installing an egg438439Installing eggs is quite straightforward on systems that support440dynamic loading (that would include *BSD, Linux, Mac OS X,441Solaris, and Windows). The command {{chicken-install}} will fetch an442egg from the master CHICKEN repository, and install it on your local443system.444445In this example, we install the {{uri-common}} egg, for parsing446Uniform Resource Identifiers.447448 $ chicken-install uri-common449450{{chicken-install}} connects to a mirror of the egg repository and451retrieves the egg contents. If the egg has any uninstalled452dependencies, it recursively installs them. Then it builds the egg453code and installs the resulting extension into the454local CHICKEN repository.455456Now we can use our new egg.457458 #;1> (import uri-common)459 ; loading /usr/lib/chicken/9/uri-common.import.so ...460 ; [... other loaded files omitted for clarity ...]461462 #;2> (uri-host (uri-reference "http://www.foobar.org/blah"))463 "www.foobar.org"464465=== Accessing C libraries466467Because CHICKEN compiles to C, and because a foreign function468interface is built into the compiler, interfacing to a C library is469quite straightforward. This means that any facility available470on the host system is accessible from CHICKEN, with more or less471work.472473Let's create a simple C library, to demonstrate how this474works. Here we have a function that will compute and return the '''n'''th475Fibonacci number. (This isn't a particularly good use of C here,476because we could write this function just as easily in Scheme, but a477real example would take far too much space here.)478479 /* fib.c */480 int fib(int n) {481 int prev = 0, curr = 1;482 int next;483 int i;484 for (i = 0; i < n; i++) {485 next = prev + curr;486 prev = curr;487 curr = next;488 }489 return curr;490 }491492Now we can call this function from CHICKEN.493494 ;;; fib-user.scm495 (import (chicken foreign) (chicken format))496497 #>498 extern int fib(int n);499 <#500 (define xfib (foreign-lambda int "fib" int))501 (do ((i 0 (+ i 1))) ((> i 10))502 (printf "~A " (xfib i)))503 (newline)504505The syntax {{#>...<#}} allows you to include literal C (typically506external declarations) in your CHICKEN code. We access {{fib}} by507defining a {{foreign-lambda}} for it, in this case saying that the508function takes one integer argument (the {{int}} after the function509name), and that it returns an integer result (the {{int}} before.) Now we can invoke510{{xfib}} as though it were an ordinary Scheme function.511512 $ gcc -c fib.c513 $ csc -o fib-user fib.o fib-user.scm514515If using MinGW on Windows,516517 > gcc -c fib.c -o fib.obj518 > csc -o fib-user fib.obj fib-user.scm519520Then run the executable.521 $ ./fib-user522 0 1 1 2 3 5 8 13 21 34 55523524Those who are interfacing to substantial C libraries should consider525using the [[/egg/bind|bind egg]].526527---528529Back to [[The User's Manual]]530531Next: [[Using the interpreter]]